package com.kyivmohyla.kma2;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.InitialContext;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MailSender {

    private static final String senderAddress = "fwo.netcracker@gmail.com";
    private static final Logger logger = Logger.getLogger("MAIL SENDER");
    private static final Level level = Level.SEVERE;
    private static MailSender instance = new MailSender();

    public static MailSender getInstance() {
        if (instance == null) {
            instance = new MailSender();
        }
        return instance;
    }

    @SuppressWarnings("UnusedParameters")
    public void sendMail(String recipient, String subject, String information) {

        try {

            InitialContext ctx = new InitialContext();
            Session session = (Session) ctx.lookup("mail/fwomail");

            // Create email and headers.
            Message msg = new MimeMessage(session);
            msg.setSubject(subject);
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient, "User"));
            //todo change this in release version
//            msg.setRecipient(Message.RecipientType.TO, new InternetAddress("fwo.netcracker@gmail.com", "User"));
            msg.setFrom(new InternetAddress(senderAddress, "User Support Robot"));

            // Body text.
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(information);

            // Multipart message.
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            msg.setContent(multipart);
            Transport.send(msg);
            logger.log(level, "message was sent successfully");

        } catch (Exception e) {
            e.printStackTrace();         //TODO bad logging. You have real logger. Why not using him ?
        }
    }
}
